﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using C1.Silverlight.DataGrid.Summaries;
using System.ServiceModel.DomainServices.Client;

namespace DYSales.Views.total
{
    public partial class mgsell_page : Page
    {
        public mgsell_page()
        {
            InitializeComponent();
            dg_sells.AutoGeneratingColumn += new EventHandler<C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs>(dg_sells_AutoGeneratingColumn);
            dg_sells_detais.AutoGeneratingColumn += new EventHandler<C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs>(dg_sells_detais_AutoGeneratingColumn);
            Loaded += new RoutedEventHandler(ExpsTotal_page_Loaded);
            bt_查询.Click += new RoutedEventHandler(bt_查询_Click);
            bt_删除.Click += new RoutedEventHandler(bt_删除_Click);
            bt_显示所有.Click += new RoutedEventHandler(bt_显示所有_Click);
            dg_sells.LoadedRowPresenter += new EventHandler<C1.Silverlight.DataGrid.DataGridRowEventArgs>(dg_sells_LoadedRowPresenter);
        }

        void dg_sells_detais_AutoGeneratingColumn(object sender, C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Property.PropertyType.Equals(typeof(decimal)) || e.Property.PropertyType.Equals(typeof(double)))
            {
                e.Column.Format = "0.##";
            }
            #region 减少列
            string headername = e.Column.Header.ToString();
            switch (headername)
            {
                case "ID":
                case "外键":
                case "进货价":
                    e.Cancel = true;
                    break;

                case "小计":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
            }
            #endregion
        }

        void dg_sells_AutoGeneratingColumn(object sender, C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Property.PropertyType.Equals(typeof(double)))
            {
                e.Column.Format = "0.##";
            }
            else if (e.Property.PropertyType.Equals(typeof(decimal)))
            {
                e.Column.Format = "0.##";
                DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
            }
            if (e.Property.PropertyType.Equals(typeof(DateTime)))
            {
                e.Column.Format = "yyyy/MM/dd HH:mm:ss";
            }
            #region 减少列
            string headername = e.Column.Header.ToString();
            switch (headername)
            {
                case "ID":
                case "外键":
                    e.Cancel = true;
                    break;
            }
            #endregion
        }

        void dg_sells_LoadedRowPresenter(object sender, C1.Silverlight.DataGrid.DataGridRowEventArgs e)
        {
            var helper = new C1.Silverlight.C1MouseHelper(e.Row.Presenter);
            helper.MouseClick += (s, a) =>
            {
                if (dg_sells.Selection.SelectedRows.Count == 1)
                {
                    var d = dg_sells.Selection.SelectedRows.First().DataItem as Web.SellTable;
                    if (d != null)
                    {
                        dg_sells_detais.DataContext = null;
                        dg_sells_detais.DataContext = d.SellDetails;
                    }
                }
            };
        }

        void bt_显示所有_Click(object sender, RoutedEventArgs e)
        {
            dm.getDS().Load(dm.getDS().GetSellTablesQuery(), lo =>
            {
                if (!lo.HasError)
                {
                    dg_sells.DataContext = lo.Entities;
                }
            }, null);
        }

        void bt_删除_Click(object sender, RoutedEventArgs e)
        {
            if (dg_sells.Selection.SelectedRows.Count >= 1)
            {
                var box = other.GetMessageBox();
                box.Closed += new EventHandler(box_Closed);
                box.Title = "东雅进销存提示";
                box.tbk_text.Text = "确定要删除选中的记录吗?";
                box.cb.Content = "是否将数量回滚到仓库？";
                box.cb.IsChecked = true;
                box.cb.Visibility = Visibility.Visible;
                box.Show();
            }
        }

        void box_Closed(object sender, EventArgs e)
        {
            var cwin = sender as cwin_Question;
            cwin.Closed -= new EventHandler(box_Closed);
            cwin.cb.Visibility = Visibility.Collapsed;
            if (cwin.DialogResult.Value)
            {
                bt_删除.IsEnabled = false;
                dm.getDS().Load(dm.getDS().GetPdTablesQuery(), LoadBehavior.RefreshCurrent, lo =>
                {
                    foreach (var item in dg_sells.Selection.SelectedRows)
                    {
                        var sell = item.DataItem as Web.SellTable;
                        if (sell != null)
                        {
                            if (cwin.cb.IsChecked.Value)
                            {
                                foreach (var sd in sell.SellDetails)
                                {
                                    var pd = dm.getDS().PdTables.FirstOrDefault(p => p.p_商品名称.Equals(sd.sd_商品名称));
                                    if (pd != null)
                                    {
                                        if (pd.p_进货价.Equals(sd.sd_进货价))
                                        {
                                            pd.p_库存数量 += sd.sd_数量;
                                        }
                                        else
                                        {
                                            var sm = ((pd.p_进货价 * pd.p_库存数量) + (sd.sd_进货价 * sd.sd_数量));
                                            pd.p_库存数量 += sd.sd_数量;
                                            pd.p_进货价 = sm / pd.p_库存数量;
                                        }
                                    }
                                }
                            }
                            dm.getDS().SellTables.Remove(sell);
                        }
                    }
                    dm.getDS().SubmitChanges(le =>
                    {
                        dg_sells.DataContext = null;
                        dg_sells.DataContext = dm.getDS().SellTables;
                        dg_sells_detais.DataContext = null;
                        bt_删除.IsEnabled = true;
                    }, null);
                }, null);
            }
        }

        void bt_查询_Click(object sender, RoutedEventArgs e)
        {
            refresh();
        }

        void ExpsTotal_page_Loaded(object sender, RoutedEventArgs e)
        {
            dm.getDS().GetST(lt =>
            {
                dm.getDS().GetSetTable(ls =>
                {
                    var lttime = lt.Value;
                    var lstime = ls.Value.s_营业开始时间;
                    var lstime2 = ls.Value.s_营业结束时间;
                    tb_startTime.DateTime = new DateTime(lttime.Year, lttime.Month, lttime.Day, lstime.Hour, lstime.Minute, lstime.Second);
                    tb_lasttime.DateTime = new DateTime(lttime.Year, lttime.Month, lttime.Day, lstime2.Hour, lstime2.Minute, lstime2.Second).AddDays(1);
                    refresh();
                }, null);
            }, null);
        }

        void refresh()
        {
            dm.getDS().Load(dm.getDS().GetSellTablesByTimeQuery(tb_startTime.DateTime.Value, tb_lasttime.DateTime.Value), lo =>
            {
                if (!lo.HasError)
                {
                    dg_sells.DataContext = lo.Entities;
                }
            }, null);
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

    }
}
